package com.matrix.async.core;

import java.net.InetAddress;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

public class RetryThread extends WorkThread {
	private DataSource dataSource = null;
	private String packageName = null;

	private int DEFAULT_RETRY_INTERVAL = 2 * 60 * 1000;
	private int retryInterval = DEFAULT_RETRY_INTERVAL;

	RetryThread(String taskType, DataSource dataSource, String packageName) {
		this.name = "[RetryThread+" + taskType + "]";
		this.taskType = taskType;
		this.dataSource = dataSource;
		this.packageName = packageName;
		this.thread = WorkThread.defaultThreadFactory().newThread(name, this);
	}

	public void setRetryInterval(int retryInterval) {
		this.retryInterval = retryInterval;
	}

	public void work() {
		retry();
		rest();
	}

	private void rest() {
		try {
			Thread.sleep(retryInterval);
		} catch (InterruptedException e) {
		}

	}

	/**
	 * 对执行时出现异常的任务进行处理，重新生成异步任务。 in_task_type 为需要恢复的任务类型
	 * in_processed_by为执行异步任务失败的服务器名称
	 * 充实线程仅在本服务器上执行失败的异步任务进行恢复，防止多台服务器并发对同一条失败的任务进行处理。
	 * 
	 */
	private void retry() {
		Connection conn = null;
		CallableStatement cs = null;
		try {
			conn = dataSource.getConnection();
			cs = conn.prepareCall("{call " + packageName + ".retry_task(?,？)}");
			cs.setString(1, taskType);
			cs.setString(2, InetAddress.getLocalHost().getHostName());
			cs.execute();
		} catch (Exception e) {
		} finally {
			if (cs != null) {
				try {
					cs.close();
				} catch (SQLException e) {
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
	}

}
